using System.Linq.Expressions;

using Volo.Abp.Domain.Entities;

namespace Volo.Abp.Domain.Repositories
{
    public static class RepositoryExtension
    {
        /// <summary>
        /// 硬删除并保存数据
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="repository"></param>
        /// <param name="entities"></param>
        /// <param name="autoSave"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public static async Task HardDeleteThenSaveAsync<TEntity>(this IRepository<TEntity> repository, IEnumerable<TEntity> entities, bool autoSave = false, CancellationToken cancellationToken = default) where TEntity : class, IEntity, ISoftDelete
        {
            await repository.HardDeleteAsync(entities, autoSave, cancellationToken);
            await repository.InsertManyAsync(entities, autoSave,cancellationToken);
            if (autoSave)
            {
                await (await repository.GetDbContextAsync()).SaveChangesAsync(cancellationToken);
            }
        }


        /// <summary>
        /// 硬删除并保存数据
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="repository"></param>
        /// <param name="predicate"></param>
        /// <param name="autoSave"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public static async Task HardDeleteThenSaveAsync<TEntity>(this IRepository<TEntity> repository, Expression<Func<TEntity, bool>> predicate, IEnumerable<TEntity> entities, bool autoSave = false, CancellationToken cancellationToken = default) where TEntity : class, IEntity, ISoftDelete
        {
            await repository.HardDeleteAsync(predicate, autoSave, cancellationToken);
            await repository.InsertManyAsync(entities, autoSave, cancellationToken);
            if (autoSave)
            {
                await (await repository.GetDbContextAsync()).SaveChangesAsync(cancellationToken);
            }
        }
    }
}
